package org.lex.depends.core.resource;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ResourceManager {
	private static final ResourceManager INSTANCE = new ResourceManager();

	public static ResourceManager getInstance() {
		return INSTANCE;
	}

	private Map<String, IResource> nameResourceMap = new HashMap<String, IResource>();
	private Map<String, File> nameLocationMap = new HashMap<String, File>();
	private Logger log = LoggerFactory.getLogger(ResourceManager.class);

	public void addJar(File jarFile) throws IOException {
		ClassUtils.loadJarResource(jarFile, nameResourceMap, nameLocationMap);
	}

	public void addDirectory(File classDir) {
		ClassUtils.loadFileSystemResource(classDir, nameResourceMap, nameLocationMap);
	}

	/**
	 * 
	 * @param name
	 *            like "java.util.List"
	 * @return
	 */
	public IResource getResource(String name) {
		return nameResourceMap.get(name);
	}

	public File getLocation(String name) {
		return this.nameLocationMap.get(name);
	}

	private ResourceManager() {
		String cp = "java.class.path";
		cp = System.getProperty(cp);
		String pathSep = "path.separator";
		String sep = System.getProperty(pathSep);
		String[] cps = cp.split(sep);
		for (String c : cps) {
			File file = new File(c);
			log.info("Add classpath: " + file);
			if (file.isDirectory()) {
				this.addDirectory(file);
			} else if (file.isFile()) {
				try {
					this.addJar(file);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}
